//
//  XGUserDetailViewController.swift
//  TodayNews
//
//  Created by monkey on 2020/2/11.
//  Copyright © 2020 itcast. All rights reserved.
//

import UIKit
import Popover
import SafariServices
import Kingfisher

/// 内部列表可用通知
let kEnableInnerScrollViewNotification = Notification.Name(rawValue: "kEnableInnerScrollViewNotification")
/// 外部列表可用通知
let kEnableOuterScrollViewNotification = Notification.Name(rawValue: "kEnableOuterScrollViewNotification")
/// 关注关系改变通知
let kFollowRelationChangedNotification: Notification.Name = Notification.Name(rawValue: "kFollowRelationChangedNotification")

// MARK: - XGUserDetailViewController

class XGUserDetailViewController: UIViewController
{
    // MARK: 构造方法
    
    init(userId: UInt64)
    {
        self.userId = userId
        
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
        XGPrint("我去了")
    }
    
    // MARK: 控制器生命周期方法
    
    override func loadView()
    {
        super.loadView()
        
        setUpUI()
    }
    
    override func viewDidLoad()
    {
        super.viewDidLoad()
        
        navigationItem.title = "用户详情"
        
        // 加载数据
        loadData()
        // 注册外部列表可用通知
        NotificationCenter.default.addObserver(self, selector: #selector(enableOuterScrollViewNotification(noti:)), name: kEnableOuterScrollViewNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(pagingViewSelectedIndexNotification(noti:)), name: kPagingViewSelectedIndexNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(statusConentCellDidSelectedNotification(noti:)), name: kStatusConentCellDidSelectedNotification, object: nil)
    }
     
    override func viewWillAppear(_ animated: Bool)
    {
        super.viewWillAppear(animated)

        navigationController?.setNavigationBarHidden(true, animated: animated)
    }
        
    override func viewWillDisappear(_ animated: Bool)
    {
        super.viewWillDisappear(animated)
                
        if viewModel.isFollowRelationChanged {
            NotificationCenter.default.post(name: kFollowRelationChangedNotification, object: nil, userInfo: nil)
        }
    }
    
    override func didReceiveMemoryWarning()
    {
        super.didReceiveMemoryWarning()
        KingfisherManager.shared.cache.clearMemoryCache()
    }
    
    // MARK: 私有属性
    
    /// 用户id
    private let userId: UInt64
    /// 视图模型
    private let viewModel: XGUserDetailViewModel = XGUserDetailViewModel()
    /// 内容视图
    private lazy var contentScrollView: UIScrollView = { [weak self] in
        let scrollView = UIScrollView()
        scrollView.backgroundColor = UIColor.white
        scrollView.contentInsetAdjustmentBehavior = .never
        scrollView.delegate = self
        return scrollView
    }()
    /// 个人信息视图
    private lazy var userDetailHeaderView: XGUserDetailHeaderView = { [weak self] in
        let headerView = XGUserDetailHeaderView()
        headerView.delegate = self
        return headerView
    }()
    /// 列表分页视图
    private lazy var pagingView: XGPagingView = XGPagingView(userId: userId)
    /// 底部tab占位视图
    private lazy var bottomTapContainerView: UIView = UIView()
    /// 导航视图
    private lazy var navBarView: XGUserDetailNavView = {
        let view = XGUserDetailNavView()
        view.alpha = 0
        view.isHidden = true
        view.delegate = self
        return view
    }()
}

// MARK: UIScrollViewDelegate

extension XGUserDetailViewController: UIScrollViewDelegate
{
    func scrollViewDidScroll(_ scrollView: UIScrollView)
    {
        // 到达最大滚动 发送通知 内部列表可用
        let offsetY = scrollView.contentOffset.y
        let max = scrollView.contentSize.height - scrollView.bounds.height
        if offsetY <= max {
            let scale = offsetY / max
            navBarView.alpha = fmax(0.0, scale)
            navBarView.isHidden = scale <= 0
        }
        
        // 控制滚动
        if offsetY >= max && contentScrollView.isScrollEnabled {
            XGPrint("外部最大")
            // 主scrollView 禁止 子scrollView滚动
            contentScrollView.showsVerticalScrollIndicator = false
            contentScrollView.isScrollEnabled = false
            NotificationCenter.default.post(name: kEnableInnerScrollViewNotification, object: nil, userInfo: nil)
        }
    }
}

// MARK: XGBottomTapViewDelegate

extension XGUserDetailViewController: XGBottomTapViewDelegate
{
    /// 底部tap被点击代理方法
    func bottomTapClick(button: UIButton, bottomTap: XGBottomTab)
    {
        if let children = bottomTap.children,
            children.count > 0 {
            // 多个
            let popover = Popover(options: [.type(.up)])
            let popoverTableView = XGPopoverTableView(children: children) { [weak popover,weak self] (bottomTabChild) in
                popover?.dismiss()
                if let url = URL(string: bottomTap.value ?? ""),bottomTap.type == "href" {
                    let webViewController = SFSafariViewController(url: url)
                    self?.present(webViewController, animated: true, completion: nil)
                }
            }
            popoverTableView.bounds = CGRect(x: 0, y: 0, width: button.bounds.width, height: 44 * CGFloat(children.count))
            popover.show(popoverTableView, fromView: button)
        } else {
            // 单个
            if let url = URL(string: bottomTap.value ?? ""),bottomTap.type == "href" {
                let webViewController = SFSafariViewController(url: url)
                self.present(webViewController, animated: true, completion: nil)
            }
        }
    }
}

// MARK: XGUserDetailHeaderViewDelegate

extension XGUserDetailViewController: XGUserDetailHeaderViewDelegate
{
    func userDetailHeaderViewFoldRecommendUser(isFold: Bool)
    {
        UIView.animate(withDuration: 0.25) {
            self.userDetailHeaderView.height = self.userDetailHeaderView.headerViewHeight
            self.pagingView.y = self.userDetailHeaderView.frame.maxY
            self.contentScrollView.contentSize = CGSize(width: 0, height: self.pagingView.frame.maxY)
        }
    }
}

// MARK: XGUserDetailNavViewDelegate

extension XGUserDetailViewController: XGUserDetailNavViewDelegate
{
    func goBackButtonClick()
    {
        navigationController?.popViewController(animated: true)
    }
    
    func titleItemDidSelected(index: Int)
    {
        pagingView.selectItemAt(index)
    }
}

// MARK: 私有扩展

private extension XGUserDetailViewController
{
    /// 动态cell内容点击通知监听方法
    @objc func statusConentCellDidSelectedNotification(noti: Notification) -> Void
    {
        guard let statusViewModel = noti.object as? XGStatusViewModel else {
            return
        }
        
        let statusDetailViewController = XGStatusDetailViewController(statusViewModel: statusViewModel)
        navigationController?.pushViewController(statusDetailViewController, animated: true)
    }
    
    /// 外部列表可用通知监听方法
    @objc func enableOuterScrollViewNotification(noti: Notification) -> Void
    {
        contentScrollView.showsVerticalScrollIndicator = true
        contentScrollView.isScrollEnabled = true
    }
    
    /// pagingView索引改变通知监听
    @objc func pagingViewSelectedIndexNotification(noti: Notification) -> Void
    {
        guard let index = noti.object as? Int else {
            return
        }
        
        navBarView.selectItemAt(index)
    }
    
    /// 加载数据
    func loadData() -> Void
    {
        // 53271122458张雪峰
        viewModel.fetchUserDetail(userId: userId) { (isSuccess) in
            if isSuccess {
                self.updateUI()
            }
        }
    }
    
    /// 设置界面
    func setUpUI() -> Void
    {
        view.theme_backgroundColor = "colors.cell_background"
        bottomTapContainerView.backgroundColor = UIColor.white
        
        view.addSubview(contentScrollView)
        view.addSubview(bottomTapContainerView)
        view.addSubview(navBarView)
        
        bottomTapContainerView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.bottom.equalTo(view.snp.bottomMargin)
            make.height.equalTo(44)
        }
        contentScrollView.snp.makeConstraints { (make) in
            make.top.left.right.equalToSuperview()
            make.bottom.equalTo(bottomTapContainerView.snp.top)
        }
        navBarView.snp.makeConstraints { (make) in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(TodayNews_NavigationBar_Height)
        }
        
        userDetailHeaderView.frame = CGRect(x: 0, y: 0, width: TodayNews_Screen_Width, height: 400)
        contentScrollView.addSubview(userDetailHeaderView)
        contentScrollView.addSubview(pagingView)
        pagingView.nav = navigationController
    }
    
    /// 更新界面
    func updateUI() -> Void
    {
        if let bottomTaps = viewModel.bottomTabs,bottomTaps.count > 0 {
            // 添加底部tab
            let bottomTapView = XGBottomTapView(bottomTaps: bottomTaps)
            bottomTapView.delegate = self
            bottomTapContainerView.addSubview(bottomTapView)
            bottomTapView.frame = CGRect(x: 0, y: 0, width: TodayNews_Screen_Width, height: 44)
        } else {
            // 隐藏底部tab
            bottomTapContainerView.snp.updateConstraints { (make) in
                make.height.equalTo(0)
            }
            view.layoutIfNeeded()
            bottomTapContainerView.isHidden = true
        }

        // 更新topView大小
        userDetailHeaderView.userDetailViewModel = viewModel
        userDetailHeaderView.frame = CGRect(x: 0, y: 0, width: TodayNews_Screen_Width, height: userDetailHeaderView.headerViewHeight)
        let height = contentScrollView.bounds.height + kSectionMenuViewHeight - TodayNews_NavigationBar_Height
        pagingView.frame = CGRect(x: 0, y: userDetailHeaderView.frame.maxY, width: TodayNews_Screen_Width, height: height)
        contentScrollView.contentSize = CGSize(width: 0, height: pagingView.frame.maxY)
        
        // 有顶部tap
        if let topTabs = viewModel.topTabs {
            pagingView.topTabs = topTabs
            navBarView.titles = topTabs.compactMap { $0.show_name }
        }
    }
}
